#include "Objects/Particle.h"
#include <random>

#include <iostream>
using namespace std;

Particle::Particle(GameState *gameState) : GameObject(gameState)
{
	addProperty("Particle");
	addProperty("NOSAVE");
	setLayer(2);

	
	init();

	m_shader = gameState->getShaderManager().getShader("particle");

	m_alive = false;
	
	

	
}


Particle::~Particle()
{
}

void Particle::init(){
	m_time = 0.0f;
	m_life = 1.0f;
	m_lifeTime = 0.3f; // segons

	m_vel = b2Vec2(0.0f,0);

	setEndColor(0.0f, 0.0f, 0.0f, 1.0f);

	m_alive = true;
}

void Particle::update(double dt){
	m_life = 1.0f-(m_time/m_lifeTime);
	b2Vec2 efVel = m_vel;
	efVel *= dt;
	m_position += efVel;

	if(m_life <= 0.0f){
		this->kill();
	}
	m_time += dt;
}

void Particle::draw(){
	b2Vec2 pos = getPosition();

	sf::Shader::bind(m_shader);

	m_shader->setParameter("life", m_life);
	//m_shader->setParameter("startColor", m_color[0], m_color[1], m_color[2], m_color[3]);
	m_shader->setParameter("endColor", m_endColor[0], m_endColor[1], m_endColor[2], m_endColor[3]);

	glColor4fv(m_color);
	glPushMatrix();
	{
		glTranslatef(pos.x, pos.y, 0); 
		glScalef(getSize().x, getSize().y, 1);
		glBegin(GL_QUADS);
		{
			glTexCoord2f(0.0f, 1.0f); glVertex3f( -0.5f, -0.5f, -0.2f);
			glTexCoord2f(1.0f, 1.0f); glVertex3f( 0.5f, -0.5f, -0.2f);
			glTexCoord2f(1.0f, 0.0f); glVertex3f( 0.5f, 0.5f, -0.2f);
			glTexCoord2f(0.0f, 0.0f); glVertex3f( -0.5f, 0.5f, -0.2f);
		}
		glEnd();
	}
	glPopMatrix();

	sf::Shader::bind(NULL);
	
}

const float* Particle::getEndColor() const{
	return m_endColor;
}


void Particle::setEndColor(float r, float g, float b, float a){
	m_endColor[0] = r;
	m_endColor[1] = g;
	m_endColor[2] = b;
	m_endColor[3] = a;
}


void Particle::setShader(Shader *shader){
	m_shader = shader;
}

void Particle::setLifeTime(float lifeTime){
	m_lifeTime = lifeTime;
}